<template>
  <div class="app-container">
     
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单编号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
   

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['record:order:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleCreateSettlement"
          
            :disabled="!canCreateSettlement"
        >创建结算单</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
     

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单编号" align="center" prop="orderId" />
      <el-table-column label="订单状态" align="center" prop="orderStatus">
        <template #default="scope">
          <dict-tag :options="order_status" :value="scope.row.orderStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="订单日期" align="center" prop="orderDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.orderDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改日期" align="center" prop="modifiedDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.modifiedDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="业务类型" align="center" prop="businessType">
        <template #default="scope">
          <dict-tag :options="business_type" :value="scope.row.businessType"/>
        </template>
      </el-table-column>
      <el-table-column label="客户编号" align="center" prop="customerId" />
      <el-table-column label="关联编号" align="center" prop="referenceId" />
      <el-table-column label="付款方式" align="center" prop="paymentMethod">
        <template #default="scope">
          <dict-tag :options="payment_meth" :value="scope.row.paymentMethod"/>
        </template>
      </el-table-column>
      <el-table-column label="订单总价" align="center" prop="orderTotal" />
      <el-table-column label="发票信息" align="center" prop="invoiceInfo" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.invoiceInfo" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="最后修改日期" align="center" prop="lastModifiedDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.lastModifiedDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改人" align="center" prop="lastModifiedBy" />
      <el-table-column label="备注" align="center" prop="note" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:order:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:order:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />


    <!-- 创建结算单对话框 -->
    <el-dialog title="创建结算单" v-model="settlementOpen" width="600px" append-to-body>
      <el-form ref="settlementRef" :model="settlementForm" :rules="settlementRules" label-width="100px">
        <el-form-item label="合作方编码" prop="partnerCode">
          <el-input v-model="settlementForm.partnerCode" placeholder="请输入合作方编码" disabled />
        </el-form-item>
        <el-form-item label="订单总金额" prop="orderAmount">
          <el-input v-model="settlementForm.orderAmount" placeholder="请输入结算总金额" disabled />
        </el-form-item>   
        <el-form-item label="协议编码" prop="agreementCode">
          <el-input v-model="settlementForm.agreementCode" placeholder="请输入协议编码" disabled />
        </el-form-item>
     
        <el-form-item label="备注信息" prop="remark">
          <el-input v-model="settlementForm.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-divider content-position="center">结算详情信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddSettlementDetail">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteSettlementDetail">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="settlementDetailList" :row-class-name="rowSettlementDetailIndex" @selection-change="handleSettlementDetailSelectionChange" ref="settlementDetailTable">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="订单编码" align="center" prop="orderCode" />
          <el-table-column label="订单金额" align="center" prop="orderAmount" />
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitSettlementForm">确 定</el-button>
          <el-button @click="cancelSettlement">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    
  </div>
</template>

<script setup name="Order">
import { listOrder} from "@/api/settled/InfluencerOrders.js";
import { createSettlement } from "@/api/settled/record.js";
import { getAgreementCodeByPartnerCode } from "@/api/settled/agreement.js";

const { proxy } = getCurrentInstance();
const { payment_meth, order_status, business_type } = proxy.useDict('payment_meth', 'order_status', 'business_type');

const orderList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const selectedOrders = ref([]);
const canCreateSettlement = ref(false);
const settlementOpen = ref(false);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderStatus: null,
    orderDate: null,
    businessType: null,
    customerId: null,
    referenceId: null,
  }, settlementForm: {
    partnerCode: '',
    orderAmount: 0,
    settlementMethod: '',
    agreementCode: '',
    currencyUnit: '',
    taxRate: 0,
    taxAmount: 0,
    remark: ''
  },  settlementRules: {
    agreementCode: [
      { required: true, message: "协议编码不能为空", trigger: "blur" }
    ],
  },
  settlementDetailList: [] // 初始化为空数组
  
});

const { queryParams, form, settlementForm, settlementRules, settlementDetailList } = toRefs(data);

/** 查询订单管理列表 */
function getList() {
  loading.value = true;
  listOrder(queryParams.value).then(response => {
    orderList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}



// 创建结算单按钮操作
async function handleCreateSettlement() {
  if (selectedOrders.value.length === 0) {
    proxy.$modal.msgWarning("请先选择订单");
    return;
  }

  // 获取第一个选中订单的博主id名称
  settlementForm.value.partnerCode = selectedOrders.value[0].referenceId;


  try {
    
    const response = await getAgreementCodeByPartnerCode(settlementForm.value.partnerCode);
    console.log("获取协议编码响应:", response); // 添加日志
    if (response.code === 200) {
      settlementForm.value.agreementCode = response.msg; // 确保 response.data.agreementCode 包含协议编码
    } else {
      proxy.$modal.msgError(response.msg || "获取协议编码失败");
      return;
    }
  } catch (error) {
    console.error("获取协议编码失败:", error);
    proxy.$modal.msgError("获取协议编码失败");
    return;
  }

  
  // 计算选中订单的总金额
  settlementForm.value.orderAmount = selectedOrders.value.reduce((sum, order) => sum + parseFloat(order.orderTotal), 0);

   // 生成结算单编码（假设后端生成，这里可以留空或生成一个临时编码）
   const settlementCode = "SETTLEMENT-" + Date.now(); // 临时编码，实际应由后端生成
  settlementForm.value.settlementCode = settlementCode;

  // 设置结算单详情列表
  settlementDetailList.value = selectedOrders.value.map((order, index) => ({
    index: index + 1,
    orderCode: order.orderId, // 订单编码
    orderAmount: order.orderTotal, // 订单金额
    settlementCode: settlementCode // 结算单编码
  }));
 // 打开结算单对话框
 settlementOpen.value = true;
}

// 取消创建结算单
function cancelSettlement() {
  settlementOpen.value = false;
  resetSettlementForm();
}


// 提交结算单表单
function submitSettlementForm() {
  proxy.$refs["settlementRef"].validate(valid => {
    if (valid) {
      // 构造提交数据
      const dataToSend = {
        ...settlementForm.value, // 结算单信息
        settlementDetailList: settlementDetailList.value // 结算明细列表
      };

      // 调用创建结算单接口
      createSettlement(dataToSend).then(response => {
        if (response.code === 200) {
          proxy.$modal.msgSuccess("结算单创建成功");
          settlementOpen.value = false; // 关闭对话框
          resetSettlementForm(); // 重置表单
          getList(); // 刷新列表
        } else {
          proxy.$modal.msgError(response.msg || "结算单创建失败");
        }
      }).catch(error => {
        proxy.$modal.msgError("结算单创建失败");
      });
    }
  });
}
// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    orderId: null,
    orderStatus: null,
    orderDate: null,
    modifiedDate: null,
    businessType: null,
    customerId: null,
    referenceId: null,
    paymentMethod: null,
    orderTotal: null,
    invoiceInfo: null,
    lastModifiedDate: null,
    lastModifiedBy: null,
    note: null
  };
  proxy.resetForm("orderRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  selectedOrders.value = selection;
  single.value = selection.length != 1;
  multiple.value = !selection.length;

  if (selection.length > 0) {
    const partnerCode = selection[0].partnerCode;
    canCreateSettlement.value = selection.every(order => order.partnerCode === partnerCode);
    settlementForm.value.partnerCode = partnerCode;
    settlementForm.value.settlementAmount = selection.reduce((sum, order) => sum + parseFloat(order.orderAmount), 0);
  } else {
    canCreateSettlement.value = false;
    settlementForm.value.partnerCode = '';
    settlementForm.value.settlementAmount = 0;
  }
}




/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/order/export', {
    ...queryParams.value
  }, `order_${new Date().getTime()}.xlsx`)
}

getList();
</script>
